package com.example.admin_beautiful.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.p6spy.engine.spy.appender.MessageFormattingStrategy;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

@Configuration
public class MybatisPlusConfig implements MessageFormattingStrategy, MetaObjectHandler {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        //定义拦截器，添加顺序：多租户、动态表名 --> 分页、乐观锁 --> SQL 性能规范、防止全表更新与删除
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //开启乐观锁
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        //开启分页Page
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        // 数据变动记录插件，配置安全阈值，例如限制批量更新或插入的记录数不超过 x 条（少用）
//        interceptor.addInnerInterceptor(new DataChangeRecorderInnerInterceptor().setBatchUpdateLimit(100));
        //防全表更新与删除插件
        interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
        return interceptor;
    }

    @Override
    public String formatMessage(int i, String now, long elapsed, String s1, String sql, String s3, String s4) {
        return StringUtils.isNotBlank(sql) ? now + " 消耗时间：" + elapsed + " ms ":"p6s无法记录！！！";
    }

    /**
     * mybatisplus自动填充（日期）
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "creationTime", LocalDateTime.class, LocalDateTime.now());
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }
}
